<template>
	<div class="company-bound-container">
		<van-cell-group>
			<!-- 单位名称选择 -->
			<!-- 单位名称选择 -->
			<search-select
				v-model="form.businessId"
				label="单位名称"
				:http-url="'/api/bizPollutionSourceInfo/listall'"
				show-text="pollutionSourceName"
				choose-value="id"
				:required="true"
				:readonly="false"
				placeholder="请选择单位名称"
				@onListSelectedChange="onCompanySelected"
			/>
			<!-- 姓名输入 -->
			<van-field v-model="form.yhmc" label="姓名" placeholder="请输入姓名" required clearable />

			<!-- 手机号输入 -->
			<van-field v-model="form.sjh" label="手机号" placeholder="请输入手机号码" required clearable :maxlength="11" />

			<!-- 短信验证码 (备用，目前注释) -->
			<!-- <van-field
        v-model="form.smsCode"
        label="短信验证码"
        placeholder="请输入短信验证码"
        center
        clearable
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :disabled="btnDisabled"
            @click="sendSmsCode"
          >
            {{ smsButtonText }}
          </van-button>
        </template>
      </van-field> -->
		</van-cell-group>

		<!-- 附件上传区域 -->
		<FormFileUpload
			v-model="form.fileData"
			label="上传附件"
			:business-id="form.id"
			big-type="ZQT_WXYHZCFJ"
			small-type="FJ"
			:required="false"
			:readonly="false"
			:max-count="10"
		/>

		<div class="tips-container">
			<div>注册附件请上传:</div>
			<div>1、委托书</div>
			<div>2、营业执照副本盖章件</div>
			<div>3、申请人身份证盖章件</div>
			<div class="download-template" @click="downloadTemplate">模板下载：委托书模板下载</div>
		</div>

		<!-- 提交按钮 -->
		<div class="submit-section">
			<van-button type="primary" block :loading="submitting" @click="submitBind"> 绑 定 </van-button>
		</div>

		<!-- 企业选择弹窗 -->
		<van-popup v-model:show="showCompanyPicker" position="bottom" :style="{ height: '40%' }">
			<van-picker :columns="companyList" :loading="companyLoading" @confirm="onCompanyConfirm" @cancel="showCompanyPicker = false" />
		</van-popup>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import SearchSelect from '../../../components/search-select'
import FormFileUpload from '../../../components/form-file-upload'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { EMPTY_BOUND, DESC_BOUND, generateId } from '../constants'
import { smsApi, companyBindApi, fileUploadApi } from '../../../api/company'
import { useCacheStore } from '../../../stores/cache'
import { useUserStore } from '../../../stores/user'
import Schema from 'async-validator'

export default {
	name: 'CompanyBound',
	components: {
		SearchSelect,
		FormFileUpload,
	},
	setup() {
		const router = useRouter()
		const cacheStore = useCacheStore()
		const userStore = useUserStore()

		// 响应式数据
		const form = reactive({ ...EMPTY_BOUND })
		const showCompanyPicker = ref(false)
		const companyList = ref([])
		const companyLoading = ref(false)
		const btnDisabled = ref(false)
		const submitting = ref(false)
		const smsButtonText = ref('获取验证码')
		const maxSecond = ref(60)

		// 初始化数据
		const initData = () => {
			form.id = generateId()

			// 获取路由参数
			const query = router.currentRoute.value.query
			if (query.businessId) {
				form.businessId = query.businessId
			}
			if (query.pollutionSourceName) {
				form.pollutionSourceName = query.pollutionSourceName
			}

			// 从用户信息中获取手机号和姓名
			userStore.loadFromCache()
			if (userStore.userInfo) {
				// 使用 phonenumber 字段获取手机号
				if (userStore.userInfo.phonenumber) {
					form.sjh = userStore.userInfo.phonenumber
					form.authType = '2'
				}
				// 使用 userName 或 loginName 获取用户姓名
				if (userStore.userInfo.userName || userStore.userInfo.loginName) {
					form.yhmc = userStore.userInfo.userName || userStore.userInfo.loginName
				}
				form.thirdUserId = userStore.userInfo.lltUserId
			}

			// 确保 fileData 数组已初始化
			if (!form.fileData) {
				form.fileData = []
			}

			console.log('初始化表单数据:', form)
			console.log('用户信息:', userStore.userInfo)
		} // 获取企业列表
		const loadCompanyList = async () => {
			try {
				companyLoading.value = true
				const res = await companyBindApi.getPollutionSourceList()

				if (res.code === '0' && res.data) {
					companyList.value = res.data.map((item) => ({
						text: item.pollutionSourceName,
						value: item.id,
						...item,
					}))
				}
			} catch (error) {
				console.error('获取企业列表失败:', error)
				showToast('获取企业列表失败')
			} finally {
				companyLoading.value = false
			}
		}

		// search-select 选中企业
		const onCompanySelected = ({ dataSelectedInfo }) => {
			form.pollutionSourceName = dataSelectedInfo.pollutionSourceName
		}

		// 发送短信验证码
		const sendSmsCode = async () => {
			if (!form.sjh || !/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(form.sjh)) {
				showToast('请输入正确手机号')
				return
			}

			try {
				btnDisabled.value = true
				const res = await smsApi.sendCode(form.sjh)

				if (res.code === '0') {
					// 开始倒计时
					let countdown = maxSecond.value
					const timer = setInterval(() => {
						if (countdown === 0) {
							clearInterval(timer)
							btnDisabled.value = false
							smsButtonText.value = '获取验证码'
							return
						}
						countdown--
						smsButtonText.value = `${countdown} S`
					}, 1000)

					showToast('验证码发送成功')
				} else {
					btnDisabled.value = false
					showToast(res.msg || '发送失败')
				}
			} catch (error) {
				btnDisabled.value = false
				console.error('发送短信失败:', error)
				showToast(error.message || '发送失败')
			}
		}

		// 下载模板
		const downloadTemplate = () => {
			const templateUrl =
				'https://wx.ksepia.com/zqt-ks-server/upload/ZQT_TZGGFJ/FJ/202212131543376571602569919006400513/202212131543536131602569985926520834.pdf'
			window.open(templateUrl, '_blank')
		}

		// 表单验证
		const validateForm = (data) => {
			return new Promise((resolve, reject) => {
				const validator = new Schema(DESC_BOUND)
				validator.validate(data, (errors, fields) => {
					if (errors) {
						// 显示所有验证错误信息
						const errorMessages = errors.map((error) => error.message).join('\n')
						showToast({
							type: 'fail',
							message: errorMessages,
							duration: 3000,
						})
						reject(errors)
					} else {
						resolve(data)
					}
				})
			})
		}

		// 提交绑定
		const submitBind = async () => {
			try {
				submitting.value = true

				// 打印表单数据用于调试
				console.log('提交表单数据:', form)

				// 表单验证
				await validateForm(form)

				// 构建提交数据
				const submitData = {
					...form,
					appid: 'h5-webapp', // H5应用标识
					evn: 'h5',
				}

				const res = await companyBindApi.bindYwdw(submitData)

				if (res.code === '0') {
					// 绑定成功后，使用缓存的code重新登录以获取最新状态
					try {
						if (userStore.isCodeValid) {
							console.log('绑定成功，使用code重新登录:', userStore.code)
							const loginResult = await userStore.loginWithCode(userStore.code)

							if (loginResult.success) {
								console.log('登录状态刷新成功，跳转到首页')
								showToast('绑定成功')
								// 延迟跳转，确保状态更新完成，添加refresh参数触发首页刷新
								setTimeout(() => {
									router.replace({ path: '/', query: { refresh: 'true' } })
								}, 500)
							} else {
								console.warn('登录状态刷新返回特殊状态:', loginResult.code)
								// 即使返回特殊状态，也跳转到首页让首页处理
								setTimeout(() => {
									router.replace({ path: '/', query: { refresh: 'true' } })
								}, 500)
							}
						} else {
							// code已过期，直接跳转首页，让首页重新处理OAuth
							console.warn('code已过期，直接跳转首页')
							setTimeout(() => {
								router.replace({ path: '/', query: { refresh: 'true' } })
							}, 500)
						}
					} catch (error) {
						console.error('刷新登录状态失败:', error)
						// 即使刷新失败，也跳转到首页
						setTimeout(() => {
							router.replace({ path: '/', query: { refresh: 'true' } })
						}, 500)
					}
				} else {
					showToast(res.msg || '绑定失败')
				}
			} catch (error) {
				console.error('绑定失败:', error)

				// 如果是表单验证错误，不再重复显示错误信息（validateForm已经显示过了）
				if (Array.isArray(error) && error.length > 0 && error[0].field) {
					// 这是表单验证错误，validateForm 已经显示了错误信息
					console.log('表单验证失败，错误信息已显示')
				} else {
					// 这是其他类型的错误（如网络错误等）
					showToast({
						type: 'fail',
						message: error.message || '绑定失败，请重试',
					})
				}
			} finally {
				submitting.value = false
			}
		}

		// 页面加载时初始化
		onMounted(() => {
			initData()
			loadCompanyList()
		})

		return {
			form,
			showCompanyPicker,
			companyList,
			companyLoading,
			btnDisabled,
			submitting,
			smsButtonText,
			sendSmsCode,
			downloadTemplate,
			submitBind,
			onCompanySelected,
		}
	},
}
</script>

<style lang="less" scoped>
.company-bound-container {
	padding: 0;
	background-color: #f7f8fa;
	min-height: 100vh;

	.tips-container {
		background-color: #f6f6f6;
		padding: 15px;
		font-size: 12px;
		margin: 16px;
		border-radius: 4px;

		> div {
			margin: 5px 0;
		}

		.download-template {
			color: #007af5;
			font-size: 14px;
			font-weight: 600;
			cursor: pointer;

			&:hover {
				text-decoration: underline;
			}
		}
	}

	.submit-section {
		margin: 16px;
	}
}

:deep(.van-cell-group) {
	margin: 0;
}

:deep(.van-field__label) {
	width: 80px;
}
</style>
